package com.smt.ejb3.tutoria.client;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import com.smt.ejb3.tutoria.callback.insideentity.Apple;
import com.smt.ejb3.tutoria.callback.insideentity.AppleManager;
import com.smt.ejb3.tutoria.usertransaction.CatManager;

public class CatClient {
	public static void main(String[] args) {
//		jta();
		userTransaction();
	}
	
	private static void jta(){
		try {
			InitialContext ctx = new InitialContext();

			CatManager service = (CatManager) ctx
					.lookup("CatManagerBean/remote");
			for(int i=0; i<10; i++){
				service.saveCat("mimi"+i);
				if (i==5){
					throw new RuntimeException("Exception thrown!");
				}
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private static void userTransaction(){
		CatManager service = null;
		UserTransaction utx = null;
		try {
			InitialContext ctx = new InitialContext();

			service = (CatManager) ctx
				.lookup("CatManagerBean/remote");
			
			utx = (UserTransaction)ctx
				.lookup("UserTransaction");
						
			utx.begin();
			
			for(int i=0; i<10; i++){
				service.saveCat("mimi"+i);
				if (i==3){
					throw new RuntimeException("Exception thrown!");
				}
			}
			
			utx.commit();

		} catch (Exception ex) {
			try {
				utx.rollback();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ex.printStackTrace();
		}
	}
}
